package com.ruoyi.manage.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.ManageRedisConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.manage.domain.User;
import com.ruoyi.manage.domain.request.AppUserRequest;
import com.ruoyi.manage.mapper.UserMapper;
import com.ruoyi.manage.service.IAppRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @Author: wwy
 * @Date: 2021/1/5 14:30
 */
@Service
public class AppRegisterServiceImpl implements IAppRegisterService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 最大循环次数
     */
    private static final int COUNT_NUMBER = 100;
    @Override
    public AjaxResult register(AppUserRequest appUserRequest) {
        if(appUserRequest == null || StringUtils.isEmpty(appUserRequest.getUsername()) || StringUtils.isEmpty(appUserRequest.getVerificationCode())|| StringUtils.isEmpty(appUserRequest.getPassword())){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        //验证账号是否重复
        User user = userMapper.findByUsername(appUserRequest.getUsername());
        if(user != null){
            return AjaxResult.error("账号已存在");
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        User user1 = new User();
        user1.setCreateTime(new Date());
        user1.setUsername(appUserRequest.getUsername());
        user1.setName(appUserRequest.getName());
        Object verificationCodeCache = valueOperations.get(ManageRedisConstants.REGISTER_CODE + appUserRequest.getUsername());
        if(verificationCodeCache != null){
            String verificationCodeCacheStr = String.valueOf(verificationCodeCache);
            if(verificationCodeCacheStr.equals(appUserRequest.getVerificationCode())){
                //短信验证成功
                try {
                    String passwordMd5 = Md5Utils.encoderByMd5(appUserRequest.getPassword());
                    user1.setPassword(passwordMd5);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                userMapper.insertUser(user1);

                return AjaxResult.success();
            }else{
                throw new CustomException("验证码错误",HttpStatus.ERROR);
            }
        }else{
            return AjaxResult.error("请重新获取验证码");
        }
    }

}
